package com.yswy.domain.framework.context;

import com.yswy.domain.entity.user.User;

/**
 * 描述：用户信息
 *
 * @author yanwei
 * @since 2023/7/13 12:43
 */
public class CurrentUserContext {

    private CurrentUserContext() {
    }

    /**
     * 线程变量隔离（每个线程都有各自的LOCAL，互不干扰）  ThreadLocal屏蔽了线程间的通讯，避免了多线程问题
     * 唯一初始化变量LOCAL
     */
    private static final ThreadLocal<User> LOCAL = new ThreadLocal<>();

    public static void put(User user) {
        //将user放入
        LOCAL.set(user);
    }

    public static User get() {
        return LOCAL.get();
    }

    public static void remove() {
        LOCAL.remove();
    }

    public static User getCurrentUser() {
        User userEntity = CurrentUserContext.get();
        if (userEntity == null) {
            return null;
        }
        return userEntity;
    }

    public static Integer getUserId() {
        User userEntity = CurrentUserContext.get();
        Integer userId = 1;
        if (userEntity != null) {
            userId = userEntity.getId();
        }
        return userId;
    }

}
